from django.shortcuts import render,redirect
from django.views import View
from .forms import *
from django.http import HttpResponse,JsonResponse
from utils.code import *
from utils.loadaddr import *
from .models import *
from cart.cartmanager import SessionCartManager



# Create your views here.
class FormTestView(View):
    def get(self,request):
        u_form = RegisterForm()
        return render(request, 'formTest.html', {'u_form': u_form})
        #return render(request,'register.html')
    def post(self,request):
        u_form =RegisterForm(request.POST)
        if u_form.is_valid():
            return HttpResponse('提交成功')
        else:
            str=''
            for key,value in u_form.errors.items():
                str = str+key+'=='+value+'<br>'
            return HttpResponse(str)
class RegisterView(View):
    def get(self,request):
        return render(request, 'register.html')


    def post(self,request):
        datas=request.POST.dict()
        register_form=RegisterForm(datas)
        if register_form.is_valid():
            user = User.register(**register_form.cleaned_data)
            request.session['user'] = user
            return  redirect('/user/usercenter')
        else:
            return render(request,'register.html',{'info':datas,'errors':register_form.errors})
class UserCenterView(View):
    def get(self,request):
        user = request.session.get('user')
        return render(request,'usercenter.html',{'user':user})



class LoginView(View):
    def get(self,request):
        redirect=request.GET.get('redirect')
        cartitems = request.GET.get('cartitems')

       # request.session.flush()
        return render(request,'login.html',{'redirect':redirect,'cartitems':cartitems})
    def post(self,request):
        try:
            user = User.login(**request.POST.dict())
            request.session['user']=user
            SessionCartManager(request.session).migrateSession2DB()
            redir= request.POST.get('redirect')
            if redir == 'cart':
                return redirect('/cart/cart.html')
            elif redir == 'order':
                return redirect('/order/?cartitems='+request.POST.get('cartitems'))

            #跳转用户中心
            return redirect('/user/usercenter')
        except UserNotExisException:
            return render(request,'login.html')

class CodeView(View):
    def get(self,request):
       #生成验证码
        img,code = gene_code()
       #jiangcode保存到session
        request.session['code']=code
        #发送到客户端
        return HttpResponse(img,content_type='image/png')

class CheckcodeView(View):
    def get(self,request):
        code = request.GET.get('code',None)

        scode = request.session.get('code','-1')
        result=(code == scode)

        return JsonResponse({'checkFlag':result})
class LogoutView(View):
    def post(self,request):
        #判断用户是否登录，如果已登录，删除session中保存的登录信息
        if 'user' in request.session :
            del request.session['user']
        return JsonResponse({'result':True})

class AddressView(View):
    def get(self,request):
        provinces = get_provinces()
        user = request.session.get('user')

        addresses = []
        for address1 in Address.objects.filter(user=user):
            name = address1.uname
            phone = address1.phone
            address,details = (lambda  a:(''.join(a[:-1]),''.join(a[-1])))(address1.address.split(','))
            addresses.append({'name':name,'phone':phone,'address':address,'details':details})

        return render(request,'address.html',{'provinces':provinces,'addresses':addresses})
    def post(self,request):
        type  = request.POST.get('type')
        provId = request.POST.get('provinceId')
        if type == '1':
            citys,areas = get_citys_areas_by_provinceid(provId)
            return  JsonResponse({'citys':citys,'areas':areas})
        elif type=='2':
            cityId = request.POST.get('cityId')
            areas = get_areas_by_cityid(cityId)
            return JsonResponse({'areas':areas})
        elif type=='3':
            #接收数据
            address = request.POST.get('address')
            name = request.POST.get('name')
            phone = request.POST.get('phone')
            user = request.session.get('user')
            if user.address_set.count()==0:
                isdefault = True
            else:
                isdefault = False
            Address.objects.create(uname=name,phone=phone,address=address,user=user,isdefault=isdefault)
            html = '''<div class='dizhi'><p>姓名：{name}</p><p>手机号：{phone}</p><p>省市：{address}</p><p>详细地址：{details}</p></div>'''

            addresses = []
            for add in user.address_set.all():
                name = add.uname
                phone = add.phone
                list = add.address.split(',')
                address = ''.join(list[:-1])
                details = list[-1]
                addresses.append(html.format(name=name,phone=phone,address=address,details=details))
            return JsonResponse({'addresses':addresses})






